import pygame,sys,random,math,datetime,colour
#pygame - the main engine
#sys - allows system commands like closing windows
#random - random number engine
#math - mathematical operations
#datetime - date and time data
#colour - simple colour dicionary (I wrote this one xD)

class sprite(object):
    """generic sprite handler"""
    def __init__(self):
        pass
    def draw(self):
        """draws a sprite with location, orientation, scale, etc etc"""
    ##this ONLY draw's sprites - I need to see exactly how pygame's rendering works - if its a "canvas" type gui then we'll need to
        ##draw everything from the bottom layer up at every frame, which will be processor-intensive. If it uses "active" drawing
        ##then the drawing of sprites can actually be handled by the entity() class OR by the sprite() class but only when 
        ##"draw_sprite" is set to TRUE (otherwise it will remove the sprite from the renderlist using another function)
        pass




##initiate ALL of the pygame modules


##define our basic parameters - size, speed, and the colour "black"


##create a graphical window with the call to "pygame.display.set_mode()".
##Pygame and SDL make this easy by defaulting to the best graphics modes for the graphics hardware.
##You can override the mode and SDL will compensate for anything the hardware cannot do.

##Pygame represents images as Surface objects. The "display.set_mode()" function creates
##a new Surface object that represents the actual displayed graphics. Any drawing you do to this
##Surface will become visible on the monitor.



#################################

def create_sprite(outline="null.png",texture="null",name="null",part="torso"):
    """creates a sprite using an outlien file and replaces its alpha with texture"""
    ###note, replace the "texture" field with "colour_###" where ### is an acceptable colour from the colour module to fill with a solid colour
    
    from PIL import Image
####    try:
    if outline[-4:] ==".png":
        outline=name[:-4]
    if texture[-4:] ==".png":
        outline=name[:-4]
    
    if part=="torso" or part == 0:
        outline_path=str("../Graphics/Sprites/Mecha/Torso/"+outline+".png")
    elif part=="head" or part == 1:
        outline_path=str("../Graphics/Sprites/Mecha/Head/"+outline+".png")
    elif part=="leg"  or part == 2:
        outline_path=str("../Graphics/Sprites/Mecha/Leg/"+outline+".png")
    elif part=="weapon" or part ==3:
        outline_path=str("../Graphics/Sprites/Mecha/Weapon/"+outline+".png")
    else:
        print "outline not found"
        
    outline = Image.open(outline_path)
    outline = outline.convert("RGBA")
    
    if texture=="null":
        size=outline.size
        rand_colour=colour.colour("random",1)
        texture = Image.new("RGB",size,rand_colour[0])
        print "added random colour",rand_colour[1]
    if texture[:7]=="colour_":
        size=outline.size
        rand_colour=colour.colour(texture[7:],1)
        texture = Image.new("RGB",size,rand_colour[0])
        print "added colour",rand_colour[1]
    else:
        texture_path=str("../Graphics/Textures/"+texture+".png")
        texture = Image.open(texture_path)
        texture = texture.convert("RGB")

    x_offset=0
    y_offset=0

    if texture.size[0] < outline.size[0] or texture.size[1] < outline.size[1]:
        ##detect if texture is smaller than outline: stretch if so.
        print texture.size
        texture=texture.resize(outline.size,Image.ANTIALIAS)
        print "Too Small: IMAGE RESIZED!"
        print texture.size
        
    if texture.size[0] > outline.size[0] or texture.size[1] > outline.size[1]:
        ##detect if texture is smaller than outline: stretch if so.
        x_offset=random.randint(0,texture.size[0]-outline.size[0])
        y_offset=random.randint(0,texture.size[1]-outline.size[1])
        print "Too Big: IMAGE Shifted!"
        print texture.size


    region = outline.crop((0,0,outline.size[0],outline.size[1]))
    texture=texture.crop((0+x_offset,0+y_offset,outline.size[0]+x_offset,outline.size[1]+y_offset))
    texture.paste(region,(0,0,outline.size[0],outline.size[1]),region)
    ##replaces the alpha-blue colour with transparent-black and saves it.
    #texture.save("../graphics/sprites/Mecha/Torso/modimage.png", "PNG")

    texture = texture.convert("RGBA")
    pixdata = texture.load()
    print "changed filetype to RGBA"
    ##I converted the original image to RGB to avoid problems with alpha-overlay: 
    ##adding the alpha channel before the last step allows me to remove the beta colour to produce the final image
    i=0
    for y in xrange(texture.size[1]):
        for x in xrange(texture.size[0]):
            if pixdata[x, y] == (0,183,239,255):
                pixdata[x, y] = (0,0,0,0)
                i+=1
    print i,"pixels were replaced in:",name,part
    savedir=str("../Schematics/mecha/"+name+"_"+part+".png")
    
    texture.save(savedir, "PNG")
    
    print "saved to:",savedir

        
